<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import myAxios from '../../../../plugins/myAxios.js'
import { ElMessage } from 'element-plus'

const route = useRoute()
const questionList = ref([])
const currentPage = ref(1)
const pageSize = 10
const total = ref(0)
const userAnswers = ref({})
const loading = ref(false)
const isSubmitted = ref(false)
const timeLeft = ref(30 * 60) // 30分钟，以秒为单位
const timer = ref(null)

// 获取路由参数
const chapterId = route.query.chapterId
const questionType = route.query.questionType
const questionCategory = route.query.questionCategory

// 获取题目列表
const fetchQuestions = async () => {
  try {
    const response = await myAxios.get(
      `/student/examination/question/page`, {
        params: {
          chapterId,
          questionType,
          questionCategory,
          current: currentPage.value,
          pageSize
        }
      }
    )
    questionList.value = response.records
    total.value = response.total
  } catch (error) {
    console.error('获取题目失败:', error)
  }
}

// 切换页面
const handlePageChange = (newPage) => {
  currentPage.value = newPage
  fetchQuestions()
}

// 选择答案
const handleSelectAnswer = (questionId, answer) => {
  userAnswers.value[questionId] = answer
}

// 提交答案
const submitAnswers = async () => {
  if (Object.keys(userAnswers.value).length === 0) {
    ElMessage.warning('请至少回答一道题目')
    return
  }

  loading.value = true
  try {
    const submitData = {
      chapterId,
      answers: Object.entries(userAnswers.value).map(([questionId, answer]) => ({
        questionId: parseInt(questionId),
        answer
      }))
    }

    await myAxios.post('/student/examination/question/submit', submitData)
    ElMessage.success('提交成功')
    isSubmitted.value = true
  } catch (error) {
    ElMessage.error('提交失败：' + error)
  } finally {
    loading.value = false
  }
}

// 格式化时间显示
const formatTime = (seconds) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 开始计时器
const startTimer = () => {
  timer.value = setInterval(() => {
    timeLeft.value--
    if (timeLeft.value <= 0) {
      clearInterval(timer.value)
      if (!isSubmitted.value) {
        submitAnswers() // 时间到自动提交
      }
    }
  }, 1000)
}

onMounted(() => {
  fetchQuestions()
  startTimer() // 添加计时器启动
})

// 组件卸载时清理计时器
onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value)
  }
})
</script>

<template>
  <div class="exam-container">
    <div class="exam-header">
      <h2>模拟考试</h2>
      <div class="header-right">
        <div class="timer" :class="{ 'warning': timeLeft <= 300 }">
          剩余时间：{{ formatTime(timeLeft) }}
        </div>
        <div class="progress">第 {{ currentPage }} 页，共 {{ Math.ceil(total / pageSize) }} 页</div>
      </div>
    </div>

    <div v-if="questionList.length" class="questions-list">
      <div v-for="(question, index) in questionList" :key="question.id" class="question-item">
        <div class="question-content">
          <span class="question-number">{{ (currentPage - 1) * pageSize + index + 1 }}. </span>
          {{ question.content }}
          <span v-if="question.isDone" class="done-mark">已做过</span>
        </div>

        <!-- 选择题选项 -->
        <div v-if="question.questionType === 1" class="options">
          <label v-for="option in ['A', 'B', 'C', 'D']"
                 :key="option"
                 class="option-item"
                 :class="{
                   'selected': userAnswers[question.id] === option,
                   'disabled': isSubmitted
                 }"
                 @click="!isSubmitted && handleSelectAnswer(question.id, option)">
            <span class="option-label">{{ option }}</span>
            <span class="option-content">{{ question['option' + option] }}</span>
          </label>
        </div>

        <!-- 综合题答题区域 -->
        <div v-else class="comprehensive">
          <textarea
            v-model="userAnswers[question.id]"
            placeholder="请在此输入你的答案"
            rows="6"
            :disabled="isSubmitted"
            @input="handleSelectAnswer(question.id, $event.target.value)"
          ></textarea>
        </div>
      </div>
    </div>

    <div class="exam-footer">
      <button
        :disabled="currentPage === 1"
        @click="handlePageChange(currentPage - 1)"
      >上一页</button>
      <span>{{ currentPage }} / {{ Math.ceil(total / pageSize) }}</span>
      <button
        :disabled="currentPage >= Math.ceil(total / pageSize)"
        @click="handlePageChange(currentPage + 1)"
      >下一页</button>
      <button
        class="submit-btn"
        :disabled="loading || isSubmitted"
        @click="submitAnswers"
      >
        {{ loading ? '提交中...' : isSubmitted ? '已提交' : '提交答案' }}
      </button>
    </div>
  </div>
</template>

<style scoped lang="less">
.exam-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;

  .exam-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;

    .header-right {
      display: flex;
      align-items: center;
      gap: 20px;
    }

    .timer {
      font-size: 16px;
      font-weight: bold;
      color: #1890ff;

      &.warning {
        color: #ff4d4f;
        animation: blink 1s infinite;
      }
    }
  }

  .questions-list {
    .question-item {
      background: #fff;
      padding: 24px;
      border-radius: 12px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
      margin-bottom: 24px;

      .question-content {
        font-size: 16px;
        line-height: 1.6;
        color: #333;
        margin-bottom: 20px;

        .question-number {
          font-weight: bold;
          color: #1890ff;
        }

        .done-mark {
          display: inline-block;
          margin-left: 10px;
          padding: 2px 8px;
          font-size: 12px;
          color: #52c41a;
          background-color: #f6ffed;
          border: 1px solid #b7eb8f;
          border-radius: 4px;
        }
      }

      .options {
        display: flex;
        flex-direction: column;
        gap: 12px;

        .option-item {
          display: flex;
          align-items: center;
          padding: 12px 16px;
          border: 1px solid #e8e8e8;
          border-radius: 8px;
          cursor: pointer;
          transition: all 0.3s;

          &:hover {
            background-color: #f5f5f5;
          }

          &.selected {
            background-color: #e6f7ff;
            border-color: #1890ff;

            .option-label {
              background-color: #1890ff;
              color: white;
            }
          }

          input[type="radio"] {
            display: none;
          }

          .option-label {
            width: 24px;
            height: 24px;
            line-height: 24px;
            text-align: center;
            border-radius: 50%;
            background-color: #f0f0f0;
            margin-right: 12px;
            font-weight: bold;
            color: #666;
          }

          .option-content {
            flex: 1;
          }

          &.disabled {
            cursor: not-allowed;
            opacity: 0.7;

            &:hover {
              background-color: transparent;
            }

            &.selected {
              background-color: #f0f0f0;
              border-color: #d9d9d9;

              .option-label {
                background-color: #d9d9d9;
              }
            }
          }
        }
      }

      .comprehensive {
        textarea {
          width: 100%;
          padding: 12px;
          border: 1px solid #e8e8e8;
          border-radius: 8px;
          resize: vertical;

          &:focus {
            outline: none;
            border-color: #1890ff;
          }

          &:disabled {
            background-color: #f5f5f5;
            cursor: not-allowed;
          }
        }
      }
    }
  }

  .exam-footer {
    margin-top: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 20px;

    span {
      font-size: 14px;
      color: #666;
    }

    button {
      padding: 8px 20px;
      border: none;
      border-radius: 4px;
      background: #1890ff;
      color: white;
      cursor: pointer;

      &:disabled {
        background: #ccc;
        cursor: not-allowed;
      }
    }

    .submit-btn {
      margin-left: 20px;
      padding: 8px 24px;
      background-color: #52c41a;

      &:disabled {
        background-color: #b7eb8f;
      }

      &:not(:disabled):hover {
        background-color: #73d13d;
      }
    }
  }
}

@keyframes blink {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}
</style>
